const mongoose = require("mongoose")
const LoginSchema = require("../schema/LoginSchema")
const LoginService = require("../services/LoginServices")
const UserService = require("../services/UserServices")
const RoleService = require("../services/RoleServices")
const PermissionServices = require("../services/PermissionServices")
const { validate, errorResponese, successResponese } = require("../utils/validate")
const { encrypto } = require("../utils/crypto")
const JWT = require("../utils/jwt")
const MenuService = require("../services/MenuServices")
const { listToTree } = require("../utils/tools")

// 登录的逻辑处理
const LoginController = {
    Login: async (req, res) => {
        // 校验表单
        const v = await validate(LoginSchema, req.body)
        // 校验失败返回失败code
        if (v) return errorResponese({ res: res, msg: v })
        
        const { username, password } = req.body
        // 加密密码比对
        let psd = encrypto(password)

        const data = await LoginService.login(username, psd)

        if (data.length == 0) return errorResponese({ res: res, msg: "登录失败,账号或密码不正确" })

        if (!data[0].status) return errorResponese({ res: res, code: "401", msg: "当前用户已被禁用" })

        // 通过登录的ID获取用户信息
        const userInfo = await UserService.find({ _id: data[0]._id })
       
        // 创建新的token返回给前端
        const token = JWT.sign({
            _id: data[0]._id,
            username: data[0].username
        }, "1h")
       
        let router = []
        let permissions = []
        // 如果存在管理员角色，则返回所有菜单和按钮
        if (userInfo[0].roles.includes(mongoose.Types.ObjectId("64083b4cc94e5ceabacb4b52"))) {
            router = await MenuService.find({status:true})
            router = listToTree(JSON.parse(JSON.stringify(router)))
            permissions = await PermissionServices.find()
            permissions = permissions.map(item => item.permission)
            return  res.send({
                code: "200",
                msg: "登录成功",
                data: {
                    token,
                    menus: router,
                    permissions,
                    userInfo:userInfo[0],
                },
            })
        }
        // 通过用户信息中的角色信息查询当前角色绑定的菜单
        let menus = []
        for (let i = 0; i < userInfo[0].roles.length; i++) {
            const item = userInfo[0].roles[i];
            let roleList = await RoleService.find({ _id: item })
            for (let i = 0; i < roleList.length; i++) {
                if (!roleList[i].status) continue;
                const ele = roleList[i].menus;
                if (menus.includes(ele)) return;
                menus.push(...ele)
            }
        }
        // 去重
        menus = [...new Set(menus)]
        if (menus && menus.length !== 0) {
            // 获取菜单列表
            let menulist = await MenuService.find({status:true})
            // 查找匹配用户的菜单
            for (let i = 0; i < menulist.length; i++) {
                const item = menulist[i];
                if (menus.includes(mongoose.Types.ObjectId(item._id).toString())) {
                    router.push(item)
                }
            }
            // 获取按钮权限
            let permissionList = await PermissionServices.find()
            for (let i = 0; i < permissionList.length; i++) {
                    const p = permissionList[i];
                    if (menus.includes(mongoose.Types.ObjectId(p._id).toString())) {
                        permissions.push(p.permission)
                    }
            }
        }
        router = listToTree(JSON.parse(JSON.stringify(router)))
        res.send({
            code: "200",
            msg: "登录成功",
            data: {
                token,
                menus: router,
                permissions,
                userInfo:userInfo[0],
            },
        })

    }
}

module.exports = LoginController
